package link.idns.g01.jdbcbridge.controller;

import java.sql.SQLException;
import java.util.List;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.pool.DruidPooledConnection;

import link.idns.g01.jdbcbridge.domain.JdbcDataSource;
import link.idns.g01.jdbcbridge.utils.JdbcUtil;
import link.idns.g01.jdbcbridge.utils.PoolManager;
import link.idns.g01.jdbcbridge.utils.Response;
import lombok.Data;

@RestController
@RequestMapping("/sql")
public class SQLController {

    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public Response<Boolean> check(@RequestBody ExecuteRequest request) {
        return Response.successWithData(true);
    }

    @Data
    public static final class ExecuteRequest {
        JdbcDataSource dataSource;
        String sql;
        List<Object> args;
    }

    @RequestMapping(value = "/execute", method = RequestMethod.POST)
    public Response<Object> execute(@RequestBody ExecuteRequest request) {
        DruidPooledConnection connection = null;
        try {
            JdbcDataSource dataSource = request.getDataSource();
            connection = PoolManager.getPooledConnection(dataSource);
            List<Object> args = request.getArgs();
            Object data = JdbcUtil.executeSql(connection, request.getSql(), args);
            return Response.successWithData(data);
        } catch (Exception e) {
            return Response.fail(e.getMessage());
        } finally {
            try {
                if (connection != null)
                    connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
